<template>
  <div class="container">
    <star-nav-bar title="我的收货地址" rightText="新增地址" @right-click="addHandle" />
    <div class="address-content">
      <div class="item" v-for="item in addressList" :key="item.id" @click="defaultHandle(item)">
        <div class="left">
          <div class="address">
            <div class="detail">
              <span>{{ item.isDefault ? '默认' : '' }}</span>
              {{ item.detail }}
            </div>
            <div class="consignee">
              <span>{{ item.consignee }}</span>
              <span>{{ item.sex === '1' ? '先生' : '女士' }}</span>
              <!-- <span>{{ item.phone ? phoneFormat(item.phone) : '' }}</span> -->
              <span>{{ phoneFormat(item.phone) }}</span>
            </div>
          </div>
        </div>
        <div class="edit" @click="editHandle(item.id)">
          <van-icon size="20" name="edit" />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { getAddressAPI, putDefaultAddressAPI } from '@/api/address'
import type { AddressResultItem } from '@/types/address'
import { phoneFormat } from '@/utils/format'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const addressList = ref<AddressResultItem[]>([])
// 获取用户地址列表
const getAddress = async () => {
  try {
    const { data } = await getAddressAPI()
    addressList.value = data
  } catch (error) {
    console.log(error)
  }
}
const addHandle = () => {
  router.push('/my/address/add')
}
const editHandle = (id: number) => {
  router.push({ path: '/my/address/add', query: { id: id } })
}
// 设置默认地址
const defaultHandle = async (item: AddressResultItem) => {
  try {
    if (!item.isDefault) {
      await putDefaultAddressAPI(item.id)
      getAddress()
    }
  } catch (error) {
    console.log(error)
  }
}
onMounted(() => {
  getAddress()
})
</script>
<style scoped lang="scss">
.item {
  max-height: 60px;
  margin: 0 20px;
  padding: 10px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #999;
}
.left {
  flex: 1;
  display: flex;
  flex-direction: column;
  .detail {
    font-weight: 600;
    margin-bottom: 5px;
  }
  .consignee {
    font-size: 14px;
    color: #999;
    span {
      margin-right: 10px;
    }
  }
}
</style>
